<!--
 * @Description: 干部等次
 * @Author: oooh
 * @Date: 2024-04-26 11:16:35
 * @LastEditors: oooh
 * @LastEditTime: 2024-08-07 19:26:37
 * @FilePath: \Civil_Servant_Performance_PC\src\views\work-approval\cadre-assessment-grades\index.vue
-->
<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-select v-model="queryParams.year" placeholder="选择年份" @change="handleYearChange">
          <el-option v-for="item in dict.type.biz_work_year_list" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.quarter" placeholder="选择季度" class="ml-10" @change="handleQuarterChange">
          <el-option v-for="item in quarterOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-cascader
          class="ml-10"
          v-model="queryParams.deptId"
          :options="deptOptions"
          :show-all-levels="false"
          :props="{ checkStrictly: true, value: 'deptId', label: 'deptName', checkStrictly: true, emitPath: false }"
          placeholder="选择站办所"
          filterable
          clearable
          @change="handleDeptChange"
          ref="CascaderRef"
        ></el-cascader>
      </el-col>
    </el-row>
    <div class="text-banner" style="flex-shrink: 0">
      <span>干部绩效管理考评等次</span>
      <el-button size="mini" type="primary" circle icon="el-icon-refresh" plain @click="handleRefresh" />
    </div>
    <div class="flex justify-between" v-hasPermi="['approval:cadre-assessment-grades:submit']">
      <div>
        <span style="font-size: 14px">批量设定：</span>
        <el-button
          size="mini"
          type="primary"
          plain
          :disabled="checkBtnDisabled('submit', work.submitMark) || !selectionList.length"
          v-show="checkBtnVisible('submit')"
          @click="handleGrade(item)"
          v-for="item in dict.type.biz_personal_work_grade"
          :key="item.value"
          >{{ item.label }}</el-button
        >
      </div>
      <div>
        <el-button
          icon="el-icon-s-claim"
          size="mini"
          type="primary"
          plain
          :disabled="checkBtnDisabled('submit', work.submitMark)"
          v-show="checkBtnVisible('submit')"
          @click="handleSaveOrSubmit('submit')"
          >提交</el-button
        >
        <el-button
          class="ml-10"
          icon="el-icon-s-claim"
          size="mini"
          type="warning"
          plain
          :disabled="checkBtnDisabled('save', work.submitMark)"
          v-show="checkBtnVisible('save')"
          @click="handleSaveOrSubmit('save')"
          >保存</el-button
        >
      </div>
    </div>
    <div class="float-right align-right mb-10">
      <approvalLogs :biz-id="work.auditLog ? work.auditLog.bizId : ''" placement="bottom-end">
        <el-button
          icon="el-icon-s-claim"
          size="mini"
          type="primary"
          plain
          :disabled="checkBtnDisabled('pass', work.submitMark)"
          @click="handleApproval('pass')"
          v-show="checkBtnVisible('pass')"
          v-hasPermi="['approval:cadre-assessment-grades:pass']"
          >审批通过</el-button
        >
      </approvalLogs>
      <approvalLogs :biz-id="work.auditLog ? work.auditLog.bizId : ''" placement="bottom-end">
        <el-button
          class="ml-10"
          icon="el-icon-s-release"
          size="mini"
          type="danger"
          plain
          :disabled="checkBtnDisabled('reject', work.submitMark)"
          v-show="checkBtnVisible('reject')"
          @click="handleApproval('reject')"
          v-hasPermi="['approval:cadre-assessment-grades:reject']"
          >审批退回</el-button
        >
      </approvalLogs>

      <approvalLogs :biz-id="work.auditLog ? work.auditLog.bizId : ''" v-show="checkBtnVisible('finish')">
        <el-button icon="el-icon-chat-line-square" size="mini" type="success" class="color-success" plain>已审批通过 </el-button>
      </approvalLogs>

      <approvalLogs :biz-id="work.auditLog ? work.auditLog.bizId : ''" v-show="checkBtnVisible('approval')">
        <el-button icon="el-icon-chat-line-square" size="mini" type="text" class="color-warning" plain> [审批中] </el-button>
      </approvalLogs>
    </div>

    <div class="table">
      <el-table
        :data="tableList"
        border
        style="width: 100%"
        height="100%"
        ref="table"
        :row-class-name="tableRowClassName"
        header-cell-class-name="table-header"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="checkSelectable"> </el-table-column>
        <el-table-column label="序号" type="index" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="站办所" align="center"> </el-table-column>

        <el-table-column prop="civilServantName" label="姓名" align="center">
          <template slot-scope="scope">
            <el-popover placement="top-start" v-if="scope.row.deptManagerMark" trigger="hover">
              <div>
                <i class="el-icon-star-on color-primary"></i>
                <span class="ml-10"> {{ scope.row.deptName }}负责人</span>
              </div>
              <i slot="reference" class="el-icon-star-on color-primary"></i>
            </el-popover>
            <span>{{ scope.row.civilServantName }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="workNatureDict" width="120" label="编制" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.biz_civil_servant_work_nature" :value="scope.row.workNatureDict"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in columns" :key="item.label" :label="item.label" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.detailsJson[index] ? scope.row.detailsJson[index].score : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="得分" align="center"> </el-table-column>

        <el-table-column prop="deptRank" label="站办所排名" align="center" v-if="hasPermi('approval:cadre-assessment-grades:view-ranking')">
        </el-table-column>
        <el-table-column prop="townRank" label="全镇排名" align="center" v-if="hasPermi('approval:cadre-assessment-grades:view-ranking')">
        </el-table-column>
        <el-table-column prop="townRank" label="全镇排名" align="center" v-if="hasPermi('approval:cadre-assessment-grades:view-ranking-range')">
          <template slot-scope="scope">
            <span>{{ formatRankingRange(scope.row.townRank) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gradeDict" label="考评等次" width="180" align="center">
          <template slot-scope="scope">
            <span class="cell-warning"></span>
            <el-select v-if="!work.submitMark" v-model="scope.row.gradeDict" placeholder="选择考评等次" @change="handleGradeChange($event, scope)">
              <el-option v-for="item in dict.type.biz_personal_work_grade" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <dict-tag v-else :options="dict.type.biz_personal_work_grade" :value="scope.row.gradeDict"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="180" align="center">
          <template slot-scope="scope">
            <p class="pre-wrap align-left">{{ scope.row.remarks || '-' }}</p>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { list, rating as listSubmit, approval } from '@/api/work-approval/cadre-assessment-grades'
import { quarterFormat } from '@/utils/quarter.js'
import { deptTreeSelect } from '@/api/system/user'
import approvalLogs from '@/components/ApprovalLog'
import { getConfigKey } from '@/api/system/config'
export default {
  name: 'cadre-assessment-grades',
  dicts: ['biz_work_year_list', 'biz_personal_work_grade', 'biz_civil_servant_work_nature'],
  components: { approvalLogs },
  data() {
    return {
      work: {},
      columns: [],
      loading: false,
      quarterOptions: [],
      tableList: [],
      deptOptions: [],
      deptGrade: {
        rank: 0.6,
        xzbz: 0.4,
        YX: { scale: 0.35 },
        LH: { scale: 0.3 },
        YB: { scale: 0.25 }
      },
      queryParams: {
        year: '',
        quarter: '',
        deptId: ''
      },
      selectionList: [],
      rankingRange: ''
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getConfigKey()
    ;(async () => {
      await this.getDeptTree()
      this.handleYearChange(new Date().getFullYear())
    })()
  },
  methods: {
    getConfigKey() {
      getConfigKey('sys.performanceGrade.rankInterval').then(res => {
        this.rankingRange = res.msg || 0
      })
    },
    // 排名范围格式
    formatRankingRange(ranking) {
      let range = '-'
      if (!this.rankingRange || this.rankingRange === 0) {
        return range
      }
      if (ranking <= this.rankingRange) {
        range = `1-${this.rankingRange}`
      } else {
        while (ranking % this.rankingRange !== 0) {
          ranking++
        }
        range = `${ranking - this.rankingRange + 1}-${ranking}`
      }
      return range
    },
    hasPermi(permi) {
      return this.$auth.hasPermi(permi)
    },
    handleGrade(raw) {
      for (let item of this.selectionList) {
        let index = this.tableList.findIndex(tableItem => tableItem == item)
        // 判断好等次是否超过限制
        let isExceed = this.gradesFilter(this.tableList[index])
        if (isExceed) {
          this.$set(this.tableList[index], 'gradeDict', '')
          return
        }
        this.$set(this.tableList[index], 'gradeDict', raw.value)
        this.gradesRankCheck(this.tableList[index], index)
      }
    },
    // 校验表格是否可选
    checkSelectable(raw, index) {
      let permi = this.$auth.hasPermiOr(['approval:cadre-assessment-grades:pass', 'approval:cadre-assessment-grades:reject'])
      if (permi) {
        return true
      } else {
        return !this.work.submitMark
      }
    },
    // 表格多选
    handleSelectionChange(selection) {
      this.selectionList = selection
    },
    // 行政编制等次占比校验
    xzbzGradesFilter() {
      // 筛选全镇好等次人数
      let filterTownGrade = this.tableList.filter(item => item.gradeDict === 'H')
      // 筛选行政编制好等次人数
      let filterXZBZList = filterTownGrade.filter(item => item.workNatureDict === 'XZBZ')
      if (filterXZBZList.length / filterTownGrade.length > this.deptGrade['xzbz']) {
        Message({
          offset: 250,
          type: 'error',
          showClose: true,
          message: `操作失败！镇机关公务员评定为好等次的不超过${this.deptGrade['xzbz'] * 100}%！`
        })
        return true
      }
      return false
    },
    // 等次占比筛选
    gradesFilter(raw) {
      let length = this.tableList.length
      // 站办所评等对应基数
      let scaleBase = this.deptGrade[raw['deptGradeDict']] ? this.deptGrade[raw['deptGradeDict']]['scale'] : 1
      // 筛选同部门且干部评等为好
      let filterGradeList = this.tableList.filter(item => item.deptId === raw.deptId && item.gradeDict === 'H')
      if (filterGradeList.length > length * scaleBase) {
        Message({
          offset: 250,
          type: 'error',
          showClose: true,
          message: `【${raw.deptName}】好等次人数不能超过站办所人数的 ${scaleBase * 100}%！`
        })
        return true
      }
      return false
    },
    // 评等排名校验
    gradesRankCheck(row, index) {
      // 是否已有排名超限提醒
      if (row['isExceed'] && row.gradeDict !== 'H') {
        this.$set(this.tableList[index], 'isExceed', false)
      } else {
        // 判断好等次人员排名
        let rank = row.joinAssessmentCivilServantCnt * this.deptGrade['rank']
        if (row.gradeDict === 'H' && row.townRank > rank) {
          this.$set(this.tableList[index], 'isExceed', true)
          Message({
            offset: 250,
            type: 'error',
            showClose: true,
            message: `好等次人员绩效管理得分需在全体干部排名前 ${this.deptGrade['rank'] * 100}%！`
          })
          return true
        } else {
          this.$set(this.tableList[index], 'isExceed', false)
        }
      }
      return false
    },
    handleGradeChange(val, scope) {
      // 判断好等次是否超过限制
      let isExceed = this.gradesFilter(scope.row)
      if (isExceed) {
        this.$set(this.tableList[scope.$index], 'gradeDict', '')
        return
      }
      this.gradesRankCheck(scope.row, scope.$index)
      this.tableList = this.tableList.slice()
    },
    // 为表格行添加特定样式
    tableRowClassName({ row, rowIndex }) {
      if (row.isExceed) {
        return 'warning-row'
      }
      return ''
    },
    popoverShow() {
      let bizId = this.work.auditLog.bizId
      this.approvalLogs(bizId).then(res => {})
    },
    formatPopoverContent() {
      let bizId = this.work.auditLog.bizId
      this.approvalLogs(bizId).then(res => {})
    },
    checkBtnDisabled(operation, mark) {
      let { auditStatusDict } = this.work.auditLog || {}
      switch (operation) {
        case 'save':
        case 'submit':
          return !this.tableList.length || mark
        case 'pass':
        case 'reject':
          return !this.tableList.length || !(auditStatusDict === 'DSH')
      }
    },
    checkBtnVisible(operation) {
      let { auditStatusDict } = this.work.auditLog || {}
      switch (operation) {
        case 'save':
        case 'submit':
        case 'pass':
        case 'reject':
          return auditStatusDict !== 'SHTG'
        case 'finish':
          return auditStatusDict === 'SHTG'
        case 'approval':
          return auditStatusDict === 'SHZ'
        default:
          break
      }
    },
    // 审批
    handleApproval(operation) {
      let params = { ...this.queryParams, auditStatusDict: 'SHTG', auditRemark: '同意' }
      if (operation === 'reject') {
        params.auditStatusDict = 'SHBTG'
        params.auditRemark = '不同意'
      }
      let content = `请输入审批意见`
      this.approvalPrompt(operation, content, params.auditRemark, params)
    },
    // 审批窗口
    approvalPrompt(operation, content, inputValue, params) {
      this.$prompt(content, '审批提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '输入审批意见',
        inputType: 'textarea',
        inputPattern: /\S/,
        inputValue: inputValue,
        inputErrorMessage: '审批意见不能为空',
        beforeClose: (action, instance, done) => {
          params.auditRemark = instance.inputValue
          if (action === 'confirm') {
            const loading = this.$loading({
              target: '.el-message-box',
              lock: true,
              text: '数据处理中',
              spinner: 'el-icon-loading',
              background: 'rgba(255,255,255,0.6)'
            })
            approval(params)
              .then(() => {
                loading.close()
                if (operation === 'pass') {
                  this.$modal.msgSuccess('已通过')
                } else if (operation === 'reject') {
                  this.$modal.msgError('已退回')
                }
                this.handleRefresh()
                done()
              })
              .catch(() => {
                loading.close()
                done()
              })
          } else {
            done()
          }
        }
      })
    },
    /** 查询站办所下拉树结构 */
    async getDeptTree() {
      await deptTreeSelect().then(response => {
        this.deptOptions = this.removeEmptyChildren(response.data)
        // this.queryParams.deptId = this.deptOptions[0].deptId
      })
    },
    // 选择站办所
    handleDeptChange() {
      this.getList()
      this.$refs.CascaderRef.dropDownVisible = false
    },
    handleSaveOrSubmit(operation) {
      let isXZBZExceed = this.xzbzGradesFilter()
      if (isXZBZExceed) return
      let submitMark = false
      if (operation === 'submit') submitMark = true
      let quarterScoreRatingList = this.tableList.map(item => {
        return { id: item.id, gradeDict: item.gradeDict }
      })
      let params = { submitMark, quarterScoreRatingList }
      listSubmit(params).then(res => {
        if (operation === 'submit') {
          this.$modal.msgSuccess('已提交')
        } else if (operation === 'save') {
          this.$modal.msgSuccess('已保存')
        }
        this.handleRefresh()
      })
    },
    // 站办所负责人评分
    manageMark(list) {
      list.filter((item, index) => {
        if (item.deptManagerMark) {
          if (item.deptGradeDict === 'YX' && !item.gradeDict) {
            this.$set(this.tableList[index], 'gradeDict', 'H')
          }
          return true
        }
      })
    },
    getList() {
      this.loading = true
      list(this.queryParams)
        .then(res => {
          this.loading = false
          this.work = res.data
          let hasRole = this.$auth.hasRole('leadershipGroup')
          if (hasRole) {
            this.tableList = res.data.submitMark ? res.data.bizList : []
          } else {
            this.tableList = res.data.bizList
          }
          this.manageMark(this.tableList)
          this.columns = res.data.bizList[0]['detailsJson'].map(item => {
            return { label: item.label, value: item.score }
          })
          this.$refs['table'].doLayout()
        })
        .catch(err => (this.loading = false))
    },

    // 刷新
    handleRefresh() {
      this.getList()
    },
    // 年度选择
    handleYearChange(year) {
      this.queryParams.year = year
      // 获取当前季度、季度列表（往年默认第一季度）
      let { quarter, quarterList } = quarterFormat(year)
      this.quarterOptions = quarterList
      this.handleQuarterChange(quarter)
    },
    // 季度选择
    handleQuarterChange(quarter) {
      this.queryParams.quarter = quarter
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
// ::v-deep .row-custom .cell-warning {
//   background-color: rgba(246, 133, 129, 0.48) !important;
// }
::v-deep .warning-row {
  background-color: rgba(246, 133, 129, 0.48);
  color: #ee2a0f;
  .el-input__inner {
    color: #ee2a0f;
  }
}
::v-deep .el-input__inner {
  background-color: transparent;
}
.el-input-number--medium {
  width: auto;
}
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .table {
    flex: 1;
    overflow-y: hidden;
  }
}
::v-deep .table-header .cell {
  white-space: pre-wrap;
}
</style>
